package com.mengze.linlee_iot_adnroid.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mengze.linlee_iot_adnroid.MainActivity
import com.mengze.linlee_iot_adnroid.R
import com.mengze.linlee_iot_adnroid.databinding.ActivityLoginBinding


class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 密码显示/隐藏切换
        binding.ivPasswordToggle.setOnClickListener {
            togglePasswordVisibility()
        }

        // 登录按钮点击
        binding.btnLogin.setOnClickListener {
            attemptLogin()
        }

        var logoImageView: ImageView = binding.logoImgView
        logoImageView.setImageResource(R.drawable.logo)
    }

    fun Context.dpToPx(dp: Float): Int {
        return (dp * resources.displayMetrics.density).toInt()
    }

    private fun togglePasswordVisibility() {
//        val isPasswordVisible = binding.etPassword.transformationMethod == null
//        binding.etPassword.transformationMethod = if (isPasswordVisible) {
//            PasswordTransformationMethod.getInstance()
//        } else {
//            null
//        }
//        binding.ivPasswordToggle.setImageResource(
//            if (isPasswordVisible) R.drawable.ic_visibility_off
//            else R.drawable.ic_visibility
//        )
//        // 移动光标到文本末尾
//        binding.etPassword.setSelection(binding.etPassword.text.length)
    }

    private fun attemptLogin() {
        val username = binding.etUsername.text.toString()
        val password = binding.etPassword.text.toString()

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(this, "请输入账号和密码", Toast.LENGTH_SHORT).show()
            return
        }

        // 模拟登录逻辑
        if (username == "admin" && password == "123456") {
            startActivity(Intent(this, MainActivity::class.java))
            finish()
        } else {
            Toast.makeText(this, "账号或密码错误", Toast.LENGTH_SHORT).show()
        }
    }


    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        currentFocus?.let {
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(it.windowToken, 0)
            it.clearFocus()
        }
        return super.dispatchTouchEvent(ev)
    }

}
